<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="veeValidateSchema"
      v-slot="{ errors }">
    <div class="user-info">
      <img v-if="qqUserInfo.figureurl_2" :src="qqUserInfo.figureurl_2" alt="" />
      <img v-else src="@/assets/images/loading.gif" alt="">
      <p>Hi，{{qqUserInfo.nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{erra:errors.mobile}" v-model="form.mobile" name='mobile'  class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{erra:errors.code}"  v-model="form.code" name='code' class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCode">{{time===0?'发送验证码':`${time}秒后发送`}}</span>
      </div>
      <div class="error">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="login">立即绑定</a>
  </Form>
</template>

<script>
import { inject, onUnmounted, reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import veeValidateSchema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  setup () {
    const qqUserInfo = inject('qqUserInfo')
    const form = reactive({
      mobile: '',
      code: ''
    })

    // resume()  启动定时器
    // pause()   停止定时器
    const time = ref(0)
    const { resume, pause } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })

    onUnmounted(() => {
      pause()
    })

    const formCom = ref(null)
    const sendCode = async () => {
      // 1. 验证手机号码是否合法
      const validataResult = await veeValidateSchema.mobile(form.mobile)
      if (validataResult === true) {
        // 🔔如果前面还有倒计时正在运行，就直接退出
        try {
          if (time.value !== 0) return
          await userQQBindCode(form.mobile)
          time.value = 60
          resume()
          Message({ type: 'success', message: '发送成功' })
        } catch (error) {
          Message({ type: 'warn', message: error.response.data.message })
        }
      } else {
        // 主动设置字段错误，用于界面提示
        formCom.value.setFieldError('mobile', validataResult)
      }
    }
    const store = useStore()
    const router = useRouter()

    const login = async () => {
      const validate = await formCom.value.validate()
      if (validate === true && qqUserInfo.value.openId) {
        try {
          const { result: userInfo } = await userQQBindLogin({
            unionId: qqUserInfo.value.openId,
            mobile: form.mobile,
            code: form.code
          })
          console.log(userInfo)
          // ✅ 1. 把 token 和 用户信息 存储起来
          store.commit('user/setUser', userInfo)
          // 2. 跳转页面（回调到登录前页面 或者 跳首页）
          router.push(store.state.user.redirectUrl)
          // 3. 登录成功提示
          Message({ type: 'success', message: '登录成功' })
        } catch (error) {
          Message({ type: 'warn', message: error.response.data.message })
        }
      } else {
        Message({ type: 'warn', message: '表单校验失败' })
      }
    }

    return { qqUserInfo, form, veeValidateSchema, sendCode, formCom, time, login }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
